package com.example.examsystem.controller;

import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.dto.UserDto;
import com.example.examsystem.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 用户管理控制器
 * 提供用户的增删改查、状态管理、角色分配等功能
 * 
 * @author system
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 分页查询用户列表
     * 支持按用户名、邮箱、启用状态进行筛选
     * 
     * @param page 页码，从0开始
     * @param size 每页大小
     * @param username 用户名（模糊查询）
     * @param email 邮箱（模糊查询）
     * @param enabled 启用状态
     * @return 分页用户数据
     */
    @GetMapping
    @PreAuthorize("hasAuthority('system:user:view')")
    public ResponseEntity<PageResponse<UserDto>> getUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Boolean enabled) {
        log.info("查询用户列表 - 页码: {}, 大小: {}, 用户名: {}, 邮箱: {}, 状态: {}", 
                page, size, username, email, enabled);
        PageResponse<UserDto> users = userService.getUsers(page, size, username, email, enabled);
        return ResponseEntity.ok(users);
    }

    /**
     * 根据ID获取单个用户详情
     * 
     * @param id 用户ID
     * @return 用户详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:view')")
    public ResponseEntity<UserDto> getUser(@PathVariable Long id) {
        log.info("获取用户详情 - ID: {}", id);
        UserDto user = userService.getUserById(id);
        return ResponseEntity.ok(user);
    }

    /**
     * 创建新用户
     * 
     * @param userDto 用户信息
     * @return 创建的用户信息
     */
    @PostMapping
    @PreAuthorize("hasAuthority('system:user:create')")
    public ResponseEntity<UserDto> createUser(@RequestBody @Valid UserDto userDto) {
        log.info("创建用户 - 用户名: {}, 邮箱: {}", userDto.getUsername(), userDto.getEmail());
        UserDto createdUser = userService.createUser(userDto);
        log.info("用户创建成功 - ID: {}", createdUser.getId());
        return ResponseEntity.ok(createdUser);
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param userDto 更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:update')")
    public ResponseEntity<UserDto> updateUser(@PathVariable Long id, @RequestBody @Valid UserDto userDto) {
        log.info("更新用户 - ID: {}, 用户名: {}", id, userDto.getUsername());
        UserDto updatedUser = userService.updateUser(id, userDto);
        log.info("用户更新成功 - ID: {}", id);
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        log.info("删除用户 - ID: {}", id);
        userService.deleteUser(id);
        log.info("用户删除成功 - ID: {}", id);
        return ResponseEntity.ok().build();
    }

    /**
     * 启用或禁用用户
     * 
     * @param id 用户ID
     * @param enabled 启用状态（true=启用，false=禁用）
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('system:user:update')")
    public ResponseEntity<Void> updateUserStatus(@PathVariable Long id, @RequestParam Boolean enabled) {
        log.info("更新用户状态 - ID: {}, 状态: {}", id, enabled ? "启用" : "禁用");
        userService.updateUserStatus(id, enabled);
        log.info("用户状态更新成功 - ID: {}", id);
        return ResponseEntity.ok().build();
    }

    /**
     * 重置用户密码
     * 
     * @param id 用户ID
     * @param newPassword 新密码
     * @return 操作结果
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasAuthority('system:user:update')")
    public ResponseEntity<Void> resetPassword(@PathVariable Long id, @RequestParam String newPassword) {
        log.info("重置用户密码 - ID: {}", id);
        userService.resetPassword(id, newPassword);
        log.info("用户密码重置成功 - ID: {}", id);
        return ResponseEntity.ok().build();
    }

    /**
     * 为用户分配角色
     * 
     * @param id 用户ID
     * @param roleIds 角色ID数组
     * @return 操作结果
     */
    @PutMapping("/{id}/roles")
    @PreAuthorize("hasAuthority('system:user:role')")
    public ResponseEntity<Void> assignRoles(@PathVariable Long id, @RequestBody Long[] roleIds) {
        log.info("为用户分配角色 - 用户ID: {}, 角色数量: {}", id, roleIds != null ? roleIds.length : 0);
        userService.assignRoles(id, roleIds);
        log.info("用户角色分配成功 - 用户ID: {}", id);
        return ResponseEntity.ok().build();
    }
}

